package icu.wdtt.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.github.pagehelper.PageHelper;
import icu.wdtt.Utils.ResultUtils;
import icu.wdtt.enumModel.HttpRequestMessage;
import icu.wdtt.exception.FilesException;
import icu.wdtt.model.Files;
import icu.wdtt.model.Result;
import icu.wdtt.model.User;
import icu.wdtt.service.FilesService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.xml.ws.spi.http.HttpContext;
import java.io.*;
import java.util.List;

@RestController
@RequestMapping("files")
@ApiModel(value = "文件接口",description = "用户文件的上传下载删除修改，普通用户权限即可使用")
public class FilesController {
    @Autowired
    private FilesService filesService;
    @Autowired
    private ResultUtils resultUtils;

    @ApiOperation(value = "查询单个文件信息",notes = "携带fid，只能查询到当前登陆用户的文件信息")
    @GetMapping(path = "get",params = "fid")
    public Result get(int fid){
        try {
            Files files = filesService.get(fid);
            if(files != null){
                return resultUtils.success(HttpRequestMessage.SUCCESS_QUERY,files);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultUtils.fail(HttpRequestMessage.FAIL_QUERY);
    }

    @ApiOperation(value = "上传文件",notes = "请将表单name设置为files,可支持多文件上传")
    @PostMapping("upFile")
    public Result upFile(MultipartFile[] files) throws Exception {

                User user = StpUtil.getSession().getModel("user",User.class);
                if(!StpUtil.isLogin()){
                    return resultUtils.fail(HttpRequestMessage.FAIL_NOT_LOGIN);
                }
            Boolean flag = filesService.add(files,user.getUid());
            if(flag){
                return resultUtils.success(HttpRequestMessage.SUCCESS_ADD);
            }

        return resultUtils.fail(HttpRequestMessage.FAIL_ADD);
    }
    @PostMapping(path = "del",params = "fid")
    public Result del(int fid){
        try {
            Boolean flag = filesService.del(fid);
            if(flag){
                return resultUtils.success(HttpRequestMessage.SUCCESS_DELETE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultUtils.fail(HttpRequestMessage.FAIL_DELETE);
    }
    @ApiOperation(value = "下载文件",notes = "携带文件的fid进行下载，请注意直接跳转新页面请求，ajax请求无法直接下载")
    @GetMapping(path = "download",params = "fid")
    public ResponseEntity<InputStreamResource> download(int fid, HttpServletRequest request) throws FilesException, FileNotFoundException, UnsupportedEncodingException {

                //获取context
                ServletContext context = request.getServletContext();
                //获取user对象
                User user = StpUtil.getSession().getModel("user",User.class);
                //获取文件对象
                Files files = filesService.download(fid, user.getUid());
                //获取MIME类型信息
                String realPath = files.getFdescribe();
                //头信息为空时 设置头信息
                if(realPath == null){
                    realPath = "application/octet-stream";
                }

                //创建流
                InputStreamResource resource = new InputStreamResource(new FileInputStream(new File(files.getFurl())));
                //直接返回即可下载
                return ResponseEntity.ok()
                        .header(HttpHeaders.CONTENT_DISPOSITION,
                                "attachment;filename="+
                                 new String(files.getFname().getBytes("UTF-8"),"iso-8859-1"))
                        .contentType(MediaType.parseMediaType(realPath)).contentLength(new File(files.getFurl()).length())
                        .body(resource);


    }

    @ApiOperation(value = "模糊查询文件(根据文件名)",notes = "只能查询用户本身上传的文件.")
    @GetMapping(path = "getByFname", params = "fname")
    public Result getByFname(String fname){
        try{
            User user = StpUtil.getSession().getModel("user",User.class);
//            if(pageNum <= 0){
//                pageNum =  1;
//            }
//            if(pageSize <= 0){
//                pageSize = 10;
//            }
//            PageHelper.startPage(pageNum,pageSize);
            List<Files> filesList = filesService.getByFname(fname, user);
            return resultUtils.success(HttpRequestMessage.SUCCESS_QUERY,filesList,filesList.size());
        }catch (Exception e){
            e.printStackTrace();
        }
        return resultUtils.fail(HttpRequestMessage.FAIL_QUERY);
    }

    @ApiOperation(value = "根据文件类型查询文件",notes = "只能查询用户本身上传的文件.其中类型请参考如下:" +
            "图片类型:image;文档类型:text;音频类型:audio;视频类型:video;其他类型:application")
    @GetMapping(path = "getByType",params = "type")
    public Result getByType(String type){
        List<Files> filesList = filesService.getByType(StpUtil.getLoginIdAsInt(),type);
        if(filesList != null){
            return resultUtils.success(HttpRequestMessage.SUCCESS_QUERY,filesList,filesList.size());
        }
        return resultUtils.fail(HttpRequestMessage.FAIL_QUERY);
    }

    @ApiOperation(value = "查询当前用户所有文件",notes = "只能查询用户本身上传的文件.")
    @GetMapping("getMainFiles")
    public Result getMainFiles(){
        int uid = StpUtil.getLoginIdAsInt();
        List<Files> filesList = filesService.getMainFiles(uid);
        if(filesList != null){
            return resultUtils.success(HttpRequestMessage.SUCCESS_QUERY,filesList,filesList.size());
        }
        return resultUtils.fail(HttpRequestMessage.FAIL_QUERY);
    }

    @ApiOperation(value = "修改文件名称",notes = "修改文件名称")
    @PostMapping(path = "modifyFilesName",params = {"fid","rname"})
    public Result modifyFilesName(int fid , String rname) throws FilesException {
        Boolean flag = filesService.modifyFilesName(fid, rname);
        if(flag){
            return resultUtils.success(HttpRequestMessage.SUCCESS_UPDATE);
        }else{
            throw new FilesException("您没有修改该文件的权限!");
        }
    }

}